package com.cyyang.shop.controller;

import java.util.List;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cyyang.shop.bean.Category;
import com.cyyang.shop.service.CatService;


@Controller
@RequestMapping("cat")
public class CatController {
	
	@Autowired
	RedisTemplate<String, Category> redisTemplate;
	
	@Reference
	CatService catService;

	@RequestMapping("list")
	public String toList() {
		return "category/list";
	}
	
	@RequestMapping("getTree")
	@ResponseBody
	public List<Category> getTree(@RequestParam(defaultValue="0")Integer id){
		
		if (redisTemplate.hasKey("getTree")) {
			List<Category> range = redisTemplate.opsForList().range("getTree", 0, -1);
			System.err.println("从reids取出");
			return range;
		} else {
			List<Category> tree = catService.getTree(id);
			redisTemplate.opsForList().rightPushAll("getTree", tree);
			System.err.println("往reids存");
			return catService.getTree(id);
		}
	}
	
	@RequestMapping("getTree1")
	@ResponseBody
	public List<Category> getTree1(@RequestParam(defaultValue="0")Integer id){
		
		return catService.getTree1();
	}
	
	@RequestMapping("add")
	@ResponseBody
	public boolean add(Category c){
		try {
			catService.add(c);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@RequestMapping("del")
	@ResponseBody
	public boolean del(Category c){
		try {
			System.out.println(c);
			catService.del(c);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@RequestMapping("update")
	@ResponseBody
	public boolean update(Category c){
		try {
			catService.update(c);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
